package com.huayun.plugin.fastener.utils;

public class LinePointCalculator {

    // 定义一个静态方法来计算新点的坐标
    public static double[] calculateNewPoint(double[] point1, double[] point2, double[] point3, double distance) {
        // 计算方向向量
        double[] directionVector = subtractPoints(point2, point1); // 可以使用 point3 - point1，结果相同

        // 单位化方向向量
        double[] unitDirectionVector = normalizeVector(directionVector);

        // 计算新点的坐标
        double[] newPoint = addScaledVector(point3, unitDirectionVector, distance);

        // 四舍五入保留四位小数
        for (int i = 0; i < newPoint.length; i++) {
            newPoint[i] = Math.round(newPoint[i] * 10000.0) / 10000.0;
        }

        return newPoint;
    }

    // 辅助方法：计算两点之间的向量差
    private static double[] subtractPoints(double[] p1, double[] p2) {
        return new double[]{p1[0] - p2[0], p1[1] - p2[1], p1[2] - p2[2]};
    }

    // 辅助方法：单位化向量
    private static double[] normalizeVector(double[] vector) {
        double magnitude = Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1] + vector[2] * vector[2]);
        return new double[]{vector[0] / magnitude, vector[1] / magnitude, vector[2] / magnitude};
    }

    // 辅助方法：将一个向量按给定比例加到点上
    private static double[] addScaledVector(double[] point, double[] vector, double scale) {
        return new double[]{point[0] + scale * vector[0], point[1] + scale * vector[1], point[2] + scale * vector[2]};
    }

    public static double calculateDistance(double[] point1, double[] point2) {
        double dx = point2[0] - point1[0];
        double dy = point2[1] - point1[1];
        double dz = point2[2] - point1[2];
        double distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
// 修改: 将距离保留三位小数
        return Math.round(distance * 1000.0) / 1000.0;
    }

//    public static void main(String[] args) {
//        // 输入参数：直线的三个点（A, B, C）和距离
//        double[] pointA = {39.081, 2.464, 61.689};
//        double[] pointB = {31.771, 31.56, 61.689}; // 注意：B点在这个计算中实际上未直接使用，但可以用于验证方向向量
//        double[] pointC = {35.426, 17.012, 61.689};
//        double distance15 = 5.0;
//        double distanceMinus15 = -5.0;
//
//        // 计算新点
//        double[] newPoint15 = calculateNewPoint(pointA, pointB, pointC, distance15);
//        double[] newPointMinus15 = calculateNewPoint(pointA, pointB, pointC, distanceMinus15);
//
//        // 输出参数：新点的坐标
//        System.out.println("New point 15 units along the line: " + arrayToString(newPoint15));
//        System.out.println("New point -15 units along the line: " + arrayToString(newPointMinus15));
//    }

    // 辅助方法：将数组转换为字符串，便于打印
    private static String arrayToString(double[] array) {
        return "(" + array[0] + ", " + array[1] + ", " + array[2] + ")";
    }
}
